import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_category_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_image_detail_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_set_backup_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_set_image_category_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_set_image_style_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_upload_confirm_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_upload_service.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

///智能家居上传页面
class SmartHomeUploadPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "SmartHomeUploadPage";

  final SmartHomeUploadItemBean itemBean;
  final List<SmartHomeUploadItemBean> itemList;
  final String shid;
  //上传完成后回到的页面
  final String router;
  final List<SpatialTypeListBean> categoryList;

  const SmartHomeUploadPage({Key key, this.itemBean, this.itemList, this.shid, this.router, this.categoryList}):super(key:key);
  ///跳转方法
  static Future<bool> navigatorPush(BuildContext context, SmartHomeUploadItemBean itemBean,
      List<SmartHomeUploadItemBean> itemList, String shid, List<SpatialTypeListBean> categoryList, {String router}){
    return RouterUtils.routeForFutureResult(
      context,
      SmartHomeUploadPage(
        itemBean: itemBean,
        itemList: itemList,
        shid: shid,
        router: router,
        categoryList: categoryList,
      ),
    );
  }

  @override
  _SmartHomeUploadPageState createState() => _SmartHomeUploadPageState();

}

class _SmartHomeUploadPageState extends BaseState<SmartHomeUploadPage>{

  ValueNotifier<int> _pageValueNotifier;
  PageController _pageController;
  SmartHomeViewModel _viewModel;
  SmartHomeStoreDetailViewModel _detailViewModel;
  @override
  void initState() {
    super.initState();
    _pageValueNotifier = ValueNotifier(0);
    _pageController = PageController(keepPage: true, initialPage: 0);
    _pageController.addListener(_changePage);
    _viewModel = new SmartHomeViewModel(this);
    _detailViewModel = new SmartHomeStoreDetailViewModel(this);
  }

  void _changePage() {
    final int currentPage = _pageController?.page?.round();
    if (currentPage != _pageValueNotifier?.value) {
      _pageValueNotifier.value = currentPage;
    }
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Color(0xFFF6F7F9),
          body: _toMainColumnWidget(),
        )
    );
  }


  @override
  void dispose() {
    _pageController?.dispose();
    _pageValueNotifier?.dispose();
    super.dispose();
  }


  Widget _toMainColumnWidget() {
    return Column(
      children: [
        _toTopBarWidget(),
        _toImagePageWidget(),
        _toBackupWidget(),
        Container(
          height: 0.5,
          color: Color(0xFFEEEEEE),
        ),
        _toBottomWidget(),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return ValueListenableBuilder(
      valueListenable: _pageValueNotifier,
      builder: (BuildContext context, int page, Widget child){
        return VgTopBarWidget(
          isShowBack: true,
          title: "${(page??1) + 1}/${widget?.itemList?.length??0}",
          titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
          backgroundColor: Colors.white,
        );
      },
    );
  }

  Widget _toImagePageWidget(){
    return Expanded(
      child: PageView(
        controller: _pageController,
        physics: ClampingScrollPhysics(),
        children: _imageWidgetList(),
      ),
    );
  }

  List<Widget> _imageWidgetList(){
    List<Widget> widgetList = new List();
    if(widget?.itemList?.isNotEmpty){
      widget?.itemList?.forEach((element) {
        widgetList.add(_toItemWidget(element));
      });
    }
    return widgetList;
  }

  Widget _toItemWidget(SmartHomeUploadItemBean itemBean){
    int picWidth = itemBean?.folderWidth;
    int picHeight = itemBean?.folderHeight;
    double scale = picHeight/picWidth;
    double maxHeight = ScreenUtils.screenH(context)
        - ScreenUtils.getStatusBarH(context)
        - ScreenUtils.getBottomBarH(context)
        - 44
        - 56
        - 50;
    double maxWidth = ScreenUtils.screenW(context);
    double width;
    double height;
    if (maxHeight / maxWidth <= scale) {
      width = maxHeight / scale;
      height = maxHeight;
    } else {
      width = maxWidth;
      height = maxWidth * scale;
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(itemBean.isVideo()){
          VgPhotoPreview.single(
              context,
              itemBean?.getPicOrVideoUrl(),
              loadingCoverUrl: itemBean.getLocalPicUrl(),
              loadingImageQualityType: ImageQualityType.high,
              photoPreviewType: PhotoPreviewType.video
          );
        }else{
          VgPhotoPreview.single(
            context,
            itemBean.getLocalPicUrl(),
            loadingImageQualityType: ImageQualityType.high,
          );
        }
      },
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
              height: height,
              width: width,
              child: VgCacheNetWorkImage(
                itemBean.getLocalPicUrl(),
                fit: BoxFit.fitWidth,
                imageQualityType: ImageQualityType.high,
              )
          ),
          Align(
            alignment: Alignment.center,
            child: Visibility(
              visible: itemBean.isVideo(),
              child: Opacity(
                opacity: 0.5,
                child: Image.asset(
                  "images/video_play_ico.png",
                  width: 52,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  ///备注信息
  Widget _toBackupWidget(){
    return ValueListenableBuilder(
      valueListenable: _pageValueNotifier,
      builder: (BuildContext context, int page, Widget child){
        int index = _pageValueNotifier?.value;
        SmartHomeUploadItemBean itemBean = widget?.itemList[index];
        String backup = itemBean?.backup??"";
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            SmartHomeSetBackupDialog.navigatorPushDialog(context, backup: backup,
                onConfirm: (value){
                  setState(() {
                    itemBean?.backup = value;
                    widget?.itemList[index] = itemBean;
                  });

                },
                onDelete: (){
                  setState(() {
                    itemBean?.backup = "";
                    widget?.itemList[index] = itemBean;
                  });
                }
            );
          },
          child: Container(
            height: 50,
            color: Colors.white,
            padding: EdgeInsets.symmetric(horizontal: 15),
            alignment: Alignment.centerLeft,
            child: Text(
              StringUtils.isNotEmpty(backup)?backup:"备注信息（50字以内）",
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                  fontSize: 14,
                  color: StringUtils.isNotEmpty(backup)?
                  ThemeRepository.getInstance().getCardBgColor_21263C()
                      :Color(0xFFB0B3BF)
              ),
            ),
          ),
        );
      },
    );
  }
  ///分类、风格信息
  Widget _toBottomWidget(){
    return Container(
      height: 50,
      margin: EdgeInsets.only(bottom: ScreenUtils.getBottomBarH(context)),
      color: Colors.white,
      child: Row(
        children: [
          _toCategoryWidget(),
          Container(
            width: 1,
            height: 14,
            color: Color(0xFFDDDDDD),
          ),
          _toStyleWidget(),
          Spacer(),
          _toNextWidget(),
        ],
      ),
    );
  }

  ///空间分类
  Widget _toCategoryWidget(){
    return ValueListenableBuilder(
      valueListenable: _pageValueNotifier,
      builder: (BuildContext context, int page, Widget child){
        int index = _pageValueNotifier?.value;
        SmartHomeUploadItemBean itemBean = widget?.itemList[index];
        String stid = itemBean?.getStid()??"";
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            SmartHomeSetImageCategoryDialog.navigatorPushDialog(context, stid, widget?.categoryList, (selectType){
              setState(() {
                itemBean?.stid = selectType?.stid;
                widget?.itemList[index] = itemBean;
              });
            });
          },
          child: Container(
            width: 100,
            height: 50,
            alignment: Alignment.center,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  _getCategoryById(stid)??"空间分类",
                  style: TextStyle(
                      fontSize: 14,
                    color: StringUtils.isNotEmpty(_getCategoryById(stid))?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0xFFB0B3BF),
                  ),
                ),
                SizedBox(width: 4,),
                Image.asset(
                  "images/icon_shape_arrow_down.png",
                  color: Color(0xFFB0B3BF),
                  width: 7,
                  height: 4,
                ),
              ],
            ),
          ),
        );
      },
    );
  }


  String _getCategoryById(String id){
    String name;
    for(int i = 0; i < widget?.categoryList?.length; i++){
      if(id == widget?.categoryList[i].stid && "全部" != widget?.categoryList[i].name){
        name = widget?.categoryList[i].name;
        break;
      }
    }
    // if("其他" == name){
    //   name = "其他空间";
    // }
    if(StringUtils.isNotEmpty(name) && (name.length??0) > 4){
      return name.substring(0, 4) + "...";
    }
    return name;
  }

  ///选择风格
  Widget _toStyleWidget(){
    return ValueListenableBuilder(
      valueListenable: _pageValueNotifier,
      builder: (BuildContext context, int page, Widget child){
        int index = _pageValueNotifier?.value;
        SmartHomeUploadItemBean itemBean = widget?.itemList[index];
        String style = itemBean?.style??"";
        String styleName = ConstantRepository.of().getStyleNameByStyle(style);
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            SmartHomeSetImageStyleDialog.navigatorPushDialog(context, style, (style){
              setState(() {
                itemBean?.style = style;
                widget?.itemList[index] = itemBean;
              });
            });
          },
          child: Container(
            width: 100,
            height: 50,
            alignment: Alignment.center,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  StringUtils.isNotEmpty(styleName)?styleName:"选择风格",
                  style: TextStyle(
                      fontSize: 14,
                      color: StringUtils.isNotEmpty(styleName)?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0xFFB0B3BF),
                  ),
                ),
                SizedBox(width: 4,),
                Image.asset(
                  "images/icon_shape_arrow_down.png",
                  color: Color(0xFFB0B3BF),
                  width: 7,
                  height: 4,
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  ///下一步
  Widget _toNextWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        if(SmartHomeImageDetailPage.ROUTER == widget?.router){
          //编辑图片，无需上传
          SmartHomeUploadItemBean itemBean = widget?.itemList[0];
          _detailViewModel.editImage(context, widget?.shid, itemBean?.picid, itemBean?.backup, itemBean?.stid, itemBean?.style, widget?.router);
          return;
        }
        print("itemList:${widget?.itemList[0].getStid()}");
        bool result = await SmartHomeUploadConfirmPage.navigatorPush(context,
            widget?.itemList, widget?.shid, widget?.categoryList,
            router: widget?.router
        );
        if(result??false){
          setState(() { });
        }else{
          setState(() { });
        }
      },
      child: Container(
        width: 90,
        height: 36,
        margin: EdgeInsets.symmetric(horizontal: 15),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          borderRadius: BorderRadius.circular(18),
        ),
        child: Text(
            (SmartHomeImageDetailPage.ROUTER == widget?.router)?"保存":"下一步",
          style: TextStyle(
            color: Colors.white,
            height: 1.2,
            fontSize: 15,
          ),
        ),
      ),
    );
  }
}

